//
//  BaseRequest.m
//  SDCarBusiness
//
//  Created by 李梦艳 on 14-12-8.
//  Copyright (c) 2014年 殷佳斌. All rights reserved.
//

#import "BaseRequest.h"

#define TouDouApiURL @"http://api.tudou.com/v6/"

@implementation BaseRequest

//添加通用参数
- (NSMutableDictionary *)addGeneralParameters:(NSDictionary *)params
{
    NSMutableDictionary * resultParam;
    
    // 如果params等于nil
    if (!params)
    {
        resultParam = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    else
    {
        resultParam = [NSMutableDictionary dictionaryWithDictionary:params];
    }
    
    // 拼接必须参数
    
    return resultParam;
}
// post 请求
- (void)sendPostRequestWithAction:(NSString *)action
                          baseUrl:(NSString *)baseUrl
                           params:(NSDictionary *)params
                          success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                          failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
     
    NSDictionary * resultParams =  [[self addGeneralParameters:params] copy];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@", baseUrl, action];
    NSLog(@"Request action = %@  URL = %@ resultParams = %@", action, urlStr, resultParams);
    
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 30;

    [[manager responseSerializer] setAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
    
    [manager POST:urlStr parameters:resultParams  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"responseObject  %@",responseObject);
        if (success) {
            success(operation,responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"错误代码:%ld", error.code);
        NSString * errorMess = @"";
        if (error.code == -1011)
        {
            errorMess = @"\n服务器异常";
        }
        else if (error.code == -1001)
        {
            errorMess = @"\n请求超时";
        }
        else
        {
            errorMess = @"\n网络异常,请检查网络";
        }
        
        NSLog(@"网络请求出错: 接口名:%@, \n传入参数 %@ 最终参数 %@ error = %@", action, params, resultParams, error);
        NSDictionary * userInfo =[NSDictionary dictionaryWithObjectsAndKeys:@"网络请求失败",NSLocalizedDescriptionKey, nil];
        NSError * customError=[NSError errorWithDomain:@"ShengDa" code:500 userInfo:userInfo];
        if (failure)
        {
            failure(operation,customError);
        }
    }];
}

///搜索视频
- (void)searchVideoWithKeyWord:(NSString *)keyWord
                                pagesNumber:(NSInteger)pages
                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSNumber *number = [NSNumber numberWithInteger:pages];
    
    NSDictionary *parameters = @{@"app_key":@"ee153d6a5d32927e",
                                 @"format":@"json",
                                 @"kw":keyWord,
                                 @"pageNo":number,
                                 @"pageSize":@12,
                                 @"orderBy":@"createTime"};
    
    [self sendPostRequestWithAction:@"video/search" baseUrl:TouDouApiURL params:parameters success:success failure:failure];
}

// 上传图片
- (void)postImage:(UIImage*)image
                  success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                  failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    NSData *imageData = UIImagePNGRepresentation(image);
    
    NSDictionary *parameters = @{@"app_key":@"ee153d6a5d32927e",
                                 @"format":@"json",
                                 @"orderBy":@"createTime"};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        // [formData appendPartWithFileURL:filePath name:@"image" error:nil];
        
        // imageData:要上传的[二进制数据]
        // name:对应网站上[URL地址中]处理文件的[字段"myfiles"]
        // fileName:要保存在服务器上的[文件名]
        // mimeType:上传文件的[image/jpeg]
        [formData appendPartWithFileData:imageData name:@"myfiles" fileName:@"123.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (success)
        {
            // 成功回调
            success(operation,responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        if (failure)
        {
            // 失败回调
            failure(operation,error);
        }
    }];
}

@end
